import React, { lazy, Suspense } from 'react';
import { MicroApp, Navigate, Outlet } from '@@/exports';
import NotFound from '@/pages/404';

export const defaultRoutes = [
  {
    name: '404',
    path: '/*',
    hideInMenu: true,
    element: <NotFound />,
  },
];

function addEmptyRoute(target: App.Route, routes: Array<App.Route>) {
  if (!routes) return;

  if (!target.children) {
    target.children = [];
  }

  routes.forEach(route => {
    route.element = <Outlet></Outlet>;
    addRoute(route, route.routes);
    target.children.push(route);
  });
}

export function addRoute(target: App.Route, routes: Array<App.Route>) {
  if (!routes) return;

  if (!target.children) {
    target.children = [];
  }

  routes
    .reverse()
    .forEach(route => {
      if (route.microApp) {
        route.element = <MicroApp name={route.microApp} />;
        addEmptyRoute(route, route.routes);
      } else if (route.component) {
        const DynamicComponent = lazy(() => import(`@/pages/${route.component}`));
        route.element = <Suspense><DynamicComponent /></Suspense>;
        addRoute(route, route.routes);
      } else if (route.redirect) {
        route.element = <Navigate to={route.redirect} />;
      }

      target.children.unshift(route);
    });
}
